package com.movieknight;

import java.util.ArrayList;
import java.util.List;

import com.github.savvasdalkitsis.jtmdb.Movie;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class AddMovieListActivity extends Activity {
	private List<Movie> displayMovies, searchResults;
    static final int PICK_MOVIE_REQUEST = 0;
	
	@Override
	protected void onCreate(Bundle savedInstancesState) {
		super.onCreate(savedInstancesState);
		Bundle extras = getIntent().getExtras();
		setTitle(getString(R.string.movieListSearchResults) + " \"" + extras.getString("searchString") + "\"");
		
		// Fetches the first 10 results.
		searchResults = MovieKnightApp.movieDownloader.getLastMovieResult();
		int maxnum = 10;
		if(maxnum > searchResults.size()) {
			maxnum = searchResults.size();
		}
		
		displayMovies = new ArrayList<Movie>();
		for(int i = 0; i < maxnum; i++) {
			displayMovies.add(searchResults.get(i));
		}
		
		ListView listView = new ListView(getBaseContext());
		listView.setAdapter(new MovieAdapter(getBaseContext(), displayMovies, (MovieKnightApp) getApplication()));
		this.setContentView(listView);
		listView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(@SuppressWarnings("rawtypes") AdapterView parent, View v, int position, long id) {
				Intent intent = new Intent(getBaseContext(), AddMovieInfoPageActivity.class);
				intent.putExtra("movieID", (int) id);
				startActivityForResult(intent, PICK_MOVIE_REQUEST);
			}
		});
	}
	
	@Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_MOVIE_REQUEST) {
            if (resultCode == RESULT_OK) {
        		Intent data2 = new Intent();
        		data2.putExtra("returnKey1", data.getExtras().getInt("returnKey1"));
        		setResult(RESULT_OK, data2);
        		finish();
            }
        }
    }
}